package com.acmedcare.framework.exchange.center.executer;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/amqp")
@Slf4j
@Api(tags = "发送消息接口，用于插件与宿主交互")
public class LocalPublishEndpoint {

  final RabbitTemplate rabbitTemplate;

  public LocalPublishEndpoint(RabbitTemplate rabbitTemplate) {
    this.rabbitTemplate = rabbitTemplate;
  }

  @PostMapping("/publish")
  @ApiOperation("发送数据到交换器")
  public ResponseEntity publish(@RequestParam String exchangeName, @RequestBody String data) {
    rabbitTemplate.setExchange(exchangeName);
    try {
      rabbitTemplate.convertAndSend(data);
    } catch (Exception e) {
      log.error(String
          .format("通道：%s消息:%s,发送失败,异常信息：%s", exchangeName, data, e.getMessage()));
    }

    return ResponseEntity.ok().build();
  }
}
